package com.sh.rbac.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sh.rbac.domain.converter.RoleConverter;
import com.sh.rbac.domain.dto.role.*;
import com.sh.rbac.domain.entity.Role;
import com.sh.rbac.domain.entity.RoleMenu;
import com.sh.rbac.mapper.RoleMapper;
import com.sh.rbac.mapper.RoleMenuMapper;
import com.sh.rbac.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lucky
 * @description 针对表【sys_role(角色表)】的数据库操作Service实现
 * @createDate 2024-04-04 21:47:19
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
        implements RoleService {

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public Page<Role> getPage(Long current, Long limit, RoleQueryDTO roleQueryDTO) {
        // 创建 page 对象，传递当前页, 每页记录数
        Page<Role> page = new Page<>(current, limit);

        // 条件参数
        String name = roleQueryDTO.getName();
        String roleKey = roleQueryDTO.getRoleKey();
        Integer status = roleQueryDTO.getStatus();

        // 构建条件
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(name), Role::getName, name)
                .like(StrUtil.isNotBlank(roleKey), Role::getRoleKey, roleKey)
                .eq(status != null, Role::getStatus, status);

        // 根据修改时间倒序
        queryWrapper.orderByDesc(Role::getUpdateTime);

        // 返回结果
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<Long> getRoleAuth(Long roleId) {
        return baseMapper.getRoleAuth(roleId);
    }

    @Override
    public Boolean saveAuth(RoleAuthDTO roleAuthDTO) {
        // 删除角色权限
        roleMenuMapper.delete(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleAuthDTO.getRoleId()));

        // 保存角色权限
        if (roleAuthDTO.getMenuIds().size() > 1) {
            roleMenuMapper.insertBatch(roleAuthDTO);
        }

        return true;
    }

    @Override
    public Boolean save(RoleSaveDTO roleSaveDTO) {
        Role role = RoleConverter.INSTANCE.toEntity(roleSaveDTO);
        return super.save(role);
    }

    @Override
    public Boolean updateById(RoleUpdateDTO roleUpdateDTO) {
        Role role = RoleConverter.INSTANCE.toEntity(roleUpdateDTO);
        return super.updateById(role);
    }

    @Override
    public Boolean updateStatus(Long id, Integer status) {
        Role role = new Role();
        role.setId(id);
        role.setStatus(status);

        return super.updateById(role);
    }
}




